<?php
declare (strict_types=1);

namespace app\command;

use app\model\agency\AgencyEarningsModel;
use app\model\agency\AgencyModel;
use app\model\order\OrderItemModel;
use app\model\order\OrderModel;
use app\model\system\SysConfigModel;
use app\model\user\UserEarningsModel;
use app\model\user\UserModel;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;

/**
 * 指令-检测收货订单-十五天自动完成计算各方利益
 * Class CheckOrderComplete
 * @package app\command
 */
class CheckOrderComplete extends Command
{
    protected function configure()
    {
        $this->setName('check_order_complete_timeout')->setDescription('the check_order_complete_timeout command');
    }

    protected function execute(Input $input, Output $output)
    {
        try {
            $res = $this->getOrderTaskComplete();//自动完成订单
            if ($res) {
                $msg = "success";
            } else {
                $msg = "error";
            }
        } catch (\Exception $e) {
            // 回滚事
            $msg = $e->getMessage();
        }
        echo "$msg";
    }


    /**
     * 自动任务-收货字后 15天内无异议 自动结算
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getOrderTaskComplete()
    {
        $system_data = SysConfigModel::getSystem();
        $day = 15;
        if (!empty($system_data)) {
            $day = $system_data['order_time'];
        }
        $day_15 = time() - (3600 * 24 * $day);
        // $day_15 = time() - 10;
        $map = [
            'order_status' => 4,
            'out_handle_status' => 0
        ];
        $order_item_model = new OrderItemModel();
//        $order_item = $order_item_model->where($map)->where('take_time', '<=', $day_15)->select();
//        $agency_earnings = [];
        $channel_earnings = [];
        $top_earnings = [];
        $top_top_earnings = [];
        $user_earnings = [];
//        foreach ($order_item as $value) {
//            //分享推荐返利
//            if (!empty($value['channel_id'])) {
//                if (!isset($channel_earnings[intval($value['channel_id'])])) {
//                    $channel_earnings[intval($value['channel_id'])]['channel_money'] = 0;
//                    $channel_earnings[intval($value['channel_id'])]['channel_id'] = $value['channel_id'];
//                } else {
//                    $channel_earnings[intval($value['channel_id'])]['channel_money'] += floatval($value['channel_money']);
//                }
//            }
//            //一级推广获利
//            if (!empty($value['top_user_id'])) {
//                if (!isset($top_earnings[intval($value['top_user_id'])])) {
//                    $top_earnings[intval($value['top_user_id'])]['top_money'] = floatval($value['top_money']);
//                    $top_earnings[intval($value['top_user_id'])]['top_user_id'] = $value['top_user_id'];
//                } else {
//                    $top_earnings[intval($value['top_user_id'])]['top_money'] += floatval($value['top_money']);
//                }
//            }
//            //二级推广获利
//            if (!empty($value['top_top_user_id'])) {
//                if (!isset($top_top_earnings[intval($value['top_top_user_id'])])) {
//                    $top_top_earnings[intval($value['top_top_user_id'])]['top_top_user_id'] = $value['top_top_user_id'];
//                    $top_top_earnings[intval($value['top_top_user_id'])]['top_top_money'] = floatval($value['top_top_money']);
//                } else {
//                    $top_top_earnings[intval($value['top_top_user_id'])]['top_top_money'] += floatval($value['top_top_money']);
//                }
//            }
//            //用户购买返利
//            if (!empty($value['user_id'])) {
//                if (!isset($user_earnings[intval($value['user_id'])])) {
//                    $user_earnings[intval($value['user_id'])]['return_money'] = floatval($value['return_money']);
//                    $user_earnings[intval($value['user_id'])]['user_id'] = $value['user_id'];
//                } else {
//                    $user_earnings[intval($value['user_id'])]['return_money'] += floatval($value['return_money']);
//                }
//            }
//        }
//        Db::startTrans();
        $up_data = [
            'order_status' => 5
        ];
        $order_item_model->where($map)->where('take_time', '<=', $day_15)->update($up_data);
        $up_data['end_date'] = date("Y-m-d H:i:s");
        $order_model = new OrderModel();
        $order_model->where($map)->where('take_time', '<=', $day_15)->update($up_data);
//        foreach ($channel_earnings as $value) {
//            $order_sn = date("YmdHis") . $value['channel_id'] . mt_rand(1000, 9999);
//            $pay_sn = "";
//            $return_data = $this->userChangeEarnings($value['channel_id'], floatval($value['channel_money']), 2, 'add', $order_sn, $pay_sn);
//            if ($return_data['code'] == 0) {
//                Db::rollback();
//                return false;
//            }
//        }
//        foreach ($top_earnings as $value) {
//            $order_sn = date("YmdHis") . $value['top_user_id'] . mt_rand(1000, 9999);
//            $pay_sn = "";
//            $return_data = $this->userChangeEarnings($value['top_user_id'], floatval($value['top_money']), 2, 'add', $order_sn, $pay_sn);
//            if ($return_data['code'] == 0) {
//                Db::rollback();
//                return false;
//            }
//        }
//        foreach ($top_top_earnings as $value) {
//            $order_sn = date("YmdHis") . $value['top_top_user_id'] . mt_rand(1000, 9999);
//            $pay_sn = "";
//            $return_data = $this->userChangeEarnings($value['top_top_user_id'], floatval($value['top_top_money']), 2, 'add', $order_sn, $pay_sn);
//            if ($return_data['code'] == 0) {
//                Db::rollback();
//                return false;
//            }
//        }
//        foreach ($user_earnings as $value) {
//            $order_sn = date("YmdHis") . $value['user_id'] . mt_rand(1000, 9999);
//            $pay_sn = "";
//            $return_data = $this->userChangeEarnings($value['user_id'], floatval($value['return_money']), 1, 'add', $order_sn, $pay_sn);
//            if ($return_data['code'] == 0) {
//                Db::rollback();
//                return false;
//            }
//        }
//        Db::commit();
        return true;
    }


    /**
     * 改变用户收益情况
     * @param $user_id
     * @param $price
     * @param int $type 1返现 2佣金 3任务 4提现
     * @param string $change
     * @param string $order_sn
     * @param string $pay_sn
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function userChangeEarnings($user_id, $price, $type = 1, $change = 'add', $order_sn = '', $pay_sn = '')
    {
        if ($price <= 0) {
            $return_data['code'] = 0;
            $return_data['msg'] = "数据不合法";
            return $return_data;
        }
        $map = [
            'id' => $user_id
        ];
        $user_model = new UserModel();
        $user_data = $user_model->where($map)->field('earnings_price')->find();
        if (empty($user_data)) {
            $return_data['code'] = 0;
            $return_data['msg'] = "用户数据不存在";
            return $return_data;
        }
        $last_price = $user_data['earnings_price'];
        $detail = "";
        switch (intval($type)) {
            // 1返现 2佣金 3任务 4提现 5支付
            case 1:
                $detail = "返现 ";
                break;
            case 2:
                $detail = "佣金 ";
                break;
            case 3:
                $detail = "任务 ";
                break;
            case 4:
                $detail = "提现";
                break;
            case 5:
                $detail = "支付";
                break;
        }
        switch ($change) {
            case 'add':
                $up_data = [
                    'earnings_price' => floatval($user_data['earnings_price']) + floatval($price)
                ];
                $detail .= "获得收益";
                $check = 0;
                break;
            case 'pay':
                $pay_price = floatval($user_data['earnings_price']) - floatval($price);
                if ($pay_price < 0) {
                    $return_data['code'] = 0;
                    $return_data['msg'] = "收益余额不足";
                    return $return_data;
                }
                $up_data = [
                    'earnings_price' => $pay_price
                ];
                $detail .= "减少收益";
                $check = 0;
                break;
            case 'extract':
                $pay_price = floatval($user_data['earnings_price']) - floatval($price);
                if ($pay_price < 0) {
                    $return_data['code'] = 0;
                    $return_data['msg'] = "收益余额不足";
                    return $return_data;
                }
                $up_data = [
                    'earnings_price' => $pay_price
                ];
                $detail .= "减少收益";
                $check = 1;
                break;
            default:
                $return_data['code'] = 0;
                $return_data['msg'] = "参数有误";
                return $return_data;
        }
        $ret = $user_model->where($map)->update($up_data);
        if ($ret !== false) {
            $earnings = [
                'user_id' => $user_id,
                'pay_sn' => $pay_sn,
                'order_sn' => $order_sn,
                'type' => $type,
                'price' => $price,
                'deposit' => 0,
                'last_price' => $last_price,
                'change' => $change,
                'detail' => $detail,
                'check' => $check
            ];
            $user_earnings_model = new UserEarningsModel();
            $ret = $user_earnings_model->addEarnings($earnings);
            if ($ret !== false) {
                $return_data['code'] = 1;
                $return_data['msg'] = "操作成功";
                return $return_data;
            }
        }
        $return_data['code'] = 0;
        $return_data['msg'] = "操作失败";
        return $return_data;
    }
}
